package com.smart.community.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smart.community.user.entity.RolePermission;
import com.smart.community.user.mapper.RolePermissionMapper;
import com.smart.community.user.service.RolePermissionService;

import io.seata.spring.annotation.GlobalTransactional;

import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色权限服务实现
 *
 * @author Wu.Liang
 * @since 2025-07-05
 */
@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements RolePermissionService {

    @Override
    @GlobalTransactional
    public void deleteByRoleId(Long roleId) throws Exception {
        if (roleId == null) {
            throw new IllegalArgumentException("角色ID不能为空");
        }
        
        LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RolePermission::getRoleId, roleId);
        
        this.remove(queryWrapper);
    }

    @Override
    @GlobalTransactional
    public List<Long> getPermissionIdsByRoleId(Long roleId) throws Exception {
        if (roleId == null) {
            throw new IllegalArgumentException("角色ID不能为空");
        }
        
        LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RolePermission::getRoleId, roleId)
                   .select(RolePermission::getPermissionId);
        
        return this.list(queryWrapper)
                  .stream()
                  .map(RolePermission::getPermissionId)
                  .collect(Collectors.toList());
    }

    @Override
    @GlobalTransactional
    public void batchInsert(List<RolePermission> rolePermissions) throws Exception {
        if (rolePermissions == null || rolePermissions.isEmpty()) {
            throw new IllegalArgumentException("角色权限列表不能为空");
        }
        
        this.saveBatch(rolePermissions);
    }
} 